package com.orangelife.mobile.complaints.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.util.OrangePhoneUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.complaints.adapter.ComplainFeedbackAdapater;
import com.orangelife.mobile.complaints.biz.Complaints;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.ScrollListView;
import com.orangelife.mobile.widget.imagegridview.ImageGridView;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by YangWei
 * on 2015/11/12.
 */
public class ComplainDetailActivity extends OrangeLifeBaseActivity {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_right)
    ImageView ivTitleRight;
    @Bind(R.id.ivHandle)
    ImageView ivHandle;
    @Bind(R.id.ivHandling)
    ImageView ivHandling;
    @Bind(R.id.ivHandled)
    ImageView ivHandled;
    @Bind(R.id.ivDone)
    ImageView ivDone;
    @Bind(R.id.btnJudge)
    Button btnJudge;
    @Bind(R.id.tvSubmitTime)
    TextView tvSubmitTime;
    @Bind(R.id.tvComplainContent)
    TextView tvComplainContent;
    @Bind(R.id.tvPlanTime)
    TextView tvPlanTime;
    @Bind(R.id.rlPlanTime)
    RelativeLayout rlPlanTime;
    @Bind(R.id.llToJudge)
    LinearLayout llToJudge;
    @Bind(R.id.gvPhoto)
    ImageGridView gvPhoto;
    @Bind(R.id.tvMyHouse)
    TextView tvMyHouse;
    @Bind(R.id.flStatus)
    FrameLayout flStatus;
    @Bind(R.id.vHandling)
    View vHandling;
    @Bind(R.id.vHandled)
    View vHandled;
    @Bind(R.id.vJudge)
    View vJudge;
    @Bind(R.id.lvFeedBack)
    ScrollListView lvFeedBack;
    ImageView ivPoints[];
    View ivLines[];

    Map<String, Object> map = new HashMap<>();
    Map<String, Object> mapDetail = new HashMap<>();
    Complaints complaints = Complaints.getInstance();

    private ComplainFeedbackAdapater<Map<String, Object>> adapter;
    private List<Map<String, Object>> data;
    int status = 0;
    static String detailComplaintID = "";
    boolean isDetailFresh = false;

    int widthLar = 0, heightLar = 0, widthSma, heightSma;
    String phone = "";
    String commName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_complain_detail);
        ButterKnife.bind(this);
        CurryApplication.getInstance().addActivity(this);
        initView();
        findView();
        setAdapter();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AddJudgementActivity.ISFRESH || isDetailFresh) {
            map.put("{complaintID}", detailComplaintID);
            dialog = DialogHelper.getInstance().createLoadingDialog(
                    ComplainDetailActivity.this, Constant.LOADING);
            dialog.show();
            complaints.getComplainDetailInfo(map, new ComplainDetailHandler(ComplainDetailActivity.this));
            isDetailFresh = false;
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        ivTitleRight.setVisibility(View.VISIBLE);
        ivTitleRight.setBackgroundResource(R.drawable.icon_phone);
        Intent data = getIntent();
        if (!StringUtil.isContainBlank(data.getStringExtra("complaintID"))) {
            detailComplaintID = data.getStringExtra("complaintID");
        } else {
            detailComplaintID = data.getStringExtra("id");
        }

        isDetailFresh = true;

        ViewGroup.LayoutParams paramsLar = flStatus.getLayoutParams();
        widthLar = paramsLar.height;
        heightLar = paramsLar.height;
        ViewGroup.LayoutParams paramsSma = ivHandle.getLayoutParams();
        widthSma = paramsSma.width;
        heightSma = paramsSma.height;
    }

    /**
     * 赋值并判断
     */
    private void findView() {
        tvTitle.setText("投诉详情");
        ivTitleRight.setOnClickListener(listener);
        ivPoints = new ImageView[]{ivHandle, ivHandling, ivHandled, ivDone};
        ivLines = new View[]{vHandling, vHandled, vJudge};
    }

    /**
     * 设置详情
     */
    private void setDetail(final Map<String, Object> map) {
        /* 判断该投诉的状态 */
        status = Integer.parseInt(String.valueOf(map.get("status")));
        for (int i = 0; i < status; i++) {
            if (i == status - 1) {
                setCurrentStatusImg(ivPoints[i]);
            } else {
                setNoStatusImg(ivPoints[i]);
            }
        }
        for (int i = 0; i < status - 1; i++) {
            if (i == 3)
                break;
            ivLines[i].setBackgroundColor(getResources().getColor(R.color.lightOrange));
        }
        switch (status) {
            case 0: // 未处理
                rlPlanTime.setVisibility(View.GONE);
                btnJudge.setVisibility(View.GONE);
                break;
            case 1: // 已接收
                rlPlanTime.setVisibility(View.VISIBLE);
                llToJudge.setVisibility(View.GONE);
                btnJudge.setVisibility(View.GONE);
                break;
            case 2: // 处理中
                rlPlanTime.setVisibility(View.VISIBLE);
                llToJudge.setVisibility(View.GONE);
                btnJudge.setVisibility(View.GONE);
                break;
            case 3: // 已完成，待评价
                rlPlanTime.setVisibility(View.VISIBLE);
                llToJudge.setVisibility(View.VISIBLE);
                btnJudge.setVisibility(View.GONE);
                llToJudge.setOnClickListener(listener);
                break;
            case 4: // 已评价
                rlPlanTime.setVisibility(View.GONE);
                btnJudge.setVisibility(View.VISIBLE);
                btnJudge.setOnClickListener(listener);
                break;
        }

        DateUtil dateUtil = new DateUtil();
        String plantime = dateUtil.tranStringForDate_1(String.valueOf(map.get("tsExpect")));
        if (!StringUtil.isBlank(plantime) && status < 3) {
            tvPlanTime.setText("预计完成时间 " + plantime);
        }

        String pics = map.get("pics").toString();
        gvPhoto.init(this, pics, "##");

        String submittime = dateUtil.tranStringForDate(String.valueOf(map.get("tscreate")));
        tvSubmitTime.setText(submittime);
        phone = String.valueOf(map.get("commPhone"));
        commName = String.valueOf(map.get("commName"));
        tvComplainContent.setText(String.valueOf(map.get("content")));


        String building = String.valueOf(map.get("buildingName"));
        String house = String.valueOf(map.get("apartmentName"));
        tvMyHouse.setText(commName + building + house);

        data= (List<Map<String, Object>>) map.get("feedbackList");
        adapter.setList(data);
        adapter.notifyDataSetChanged();
    }

    private void setAdapter() {
        data = new ArrayList<>();
        adapter = new ComplainFeedbackAdapater<>(this,data);
        lvFeedBack.setAdapter(adapter);
        lvFeedBack.setFocusable(false);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.iv_title_right:
                    if (StringUtil.isContainBlank(phone)) {
                        OrangePhoneUtil.callCustomerService2(ComplainDetailActivity.this);
                    }else{
                        OrangePhoneUtil.callCommProperty(ComplainDetailActivity.this,phone,commName);
                    }
                    break;
                case R.id.btnJudge:
                    toJudgeOrLook();
                    break;
                case R.id.llToJudge:
                    toJudgeOrLook();
                    break;
            }

        }
    };


    private void toJudgeOrLook() {
        final Map<String, Object> mapJudge = new HashMap<>();
        mapJudge.put("complaintID", detailComplaintID);
        mapJudge.put("status", status);
        mapJudge.put("isScore", String.valueOf(mapDetail.get("isScore")));
        mapJudge.put("score", String.valueOf(mapDetail.get("score")));
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("judge", (Serializable) mapJudge);
        intent.putExtras(bundle);
        intent.setClass(ComplainDetailActivity.this, AddJudgementActivity.class);
        startActivity(intent);
    }

    /**
     * 设置当前状态圆点的大小
     *
     * @param iv
     */
    private void setCurrentStatusImg(ImageView iv) {
        ViewGroup.LayoutParams paramsHandled = iv.getLayoutParams();
        paramsHandled.width = widthLar;
        paramsHandled.height = heightLar;
        iv.setLayoutParams(paramsHandled);
        iv.setImageResource(R.drawable.checkwhite);
        iv.setBackgroundResource(R.drawable.dot_round_orange);
    }

    private void setNoStatusImg(ImageView iv) {
        ViewGroup.LayoutParams paramsHandled = iv.getLayoutParams();
        paramsHandled.width = widthSma;
        paramsHandled.height = heightSma;
        iv.setLayoutParams(paramsHandled);
        iv.setImageResource(R.color.transparent);
        iv.setBackgroundResource(R.drawable.dot_round_orange);
    }

    static class ComplainDetailHandler extends Handler {
        private WeakReference<ComplainDetailActivity> complainDetailActivity = null;

        public ComplainDetailHandler(ComplainDetailActivity activity) {
            complainDetailActivity = new WeakReference<ComplainDetailActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ComplainDetailActivity act = complainDetailActivity.get();

            if (act != null) {
                switch (msg.what) {
                    case 2:
                        act.mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                                msg.obj.toString()).get("entity");
                        act.setDetail(act.mapDetail);
                        break;
                    case 500:
                        DialogHelper.closeDialog(act.dialog);
                        ToastHelper.getInstance()._toast("网络连接超时，请重新请求...");
                        break;
                    case 1011:
                        act.isLogin(act.dialog);
                        break;

                    default:
                        break;
                }

                if (act.dialog != null) {
                    act.dialog.dismiss();
                }
            }
        }
    }


    public void onBackClick() {
        finish();
    }
}
